package com.emm.yixun.mobile.base;

import android.R;
import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.emm.yixun.mobile.application.EmmApplication;
import com.emm.yixun.mobile.login.LoginActivity;
import com.emm.yixun.utils.ToastUtils;
import com.eroad.product.tools.PopuContent;
import com.eroad.product.tools.SystemBarTintManager;

import xf.tools.Loading;

@SuppressLint("NewApi")
public class BaseActivity extends FragmentActivity {

    private static final String TAG = "BaseActivity";

    public static Activity activity;

    /**
     * 缓存时间
     */
    private static long lastClickTime;

    /**
     * 状态栏高度
     */
    public static int statusBarHeight;

    int i = 0;

    /**
     * 是否显示状态栏（全屏或非全屏）默认true
     */
    protected boolean IsVisibleStatusBar = true;

    @Override
    protected void onCreate(Bundle arg0) {
        SetLogCat("onCreate()");
        super.onCreate(arg0);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏
        if (IsVisibleStatusBar) {
            SetTopTitleBgcolor();
            // activity = this;
            if (i == 0) {
                i++;
                statusBarHeight = GetstatusBarHeight();
            }
        } else {
            IsVisibleStatusBar = true;
        }
    }

    @Override
    protected void onResume() {
        // SetLogCat("onResume()");
        super.onResume();
        IntentFilter filter = new IntentFilter("OpenLogin_Besa");
        filter.addAction("108E65843mYuwqb01X");
        registerReceiver(mBroadcastReceiver, filter);
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if ("OpenLogin_Besa".equals(action)) {
                Log.v("TAG", "到登录界面");
                EmmApplication.Ts("请重新登录");
                Intent intents = new Intent(activity, LoginActivity.class);
                intents.putExtra("isonresume", "1");
                activity.startActivity(intents);
                activity.finish();
                Log.v("TAG", "关闭该界面");
            }
            if ("108E65843mYuwqb01X".equals(action)) {
                PopuContent.poPu(activity, "账号权限发生变动，请重新登录", false, 77);
                Log.v("TAG", "账号权限发生变动，请重新登录");
            }
        }
    };

    @Override
    protected void onStart() {
        // SetLogCat("onStart()");
        super.onStart();
    }

    @Override
    protected void onStop() {
        // SetLogCat("onStop()");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        // SetLogCat("onDestroy()");
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    protected void onRestart() {
        // SetLogCat("onRestart()");
        super.onRestart();
    }

    private void SetLogCat(String str) {
        // Log.i("BaseActivity-->", str);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isFastDoubleClick()) {
                Log.v("dispatchTouchEvent::>", "间隔过短，此次点击无效");
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        lastClickTime = time;
        return timeD <= 200;
    }

    /**
     * 设置顶部title背景颜色 此处设置值为：透明
     */
    public void SetTopTitleBgcolor() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.transparent);// 通知栏所需颜色
        }
    }

    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    /**
     * 设置view的高度
     */
    public static void SetViewHeight(RelativeLayout top_heads) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, statusBarHeight
                + top_heads.getLayoutParams().height);
        top_heads.setLayoutParams(lp);
        top_heads.setPadding(0, 0, 0, 0);
    }

    /**
     * 获取状态栏高度
     */
    private int GetstatusBarHeight() {
        int statusBarHeight = -1;
        // 获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            // 根据资源ID获取响应的尺寸值
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }
        Log.v(TAG, "statusBarHeight:" + statusBarHeight);
        return statusBarHeight;
    }

    /**
     * <p>
     * <b>Title：</b> 设置view的高度及padding值
     * </p>
     * <p>
     * <b>Description：</b>继承于baseactivity，并使用@layout/main_head_title可调用此方法
     * </p>
     *
     * @param id
     * @author tangxin
     * @date 2016年12月23日 下午3:54:23
     */
    public void SetRelativiLayoutPadding(int id) {
        RelativeLayout main_head_top_rela = (RelativeLayout) findViewById(id);
        SetViewHeight(main_head_top_rela);// 更改relativelayout的高度
    }

    public static void SetViewPaddingHeight(RelativeLayout top_heads, int height) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                EmmApplication.dip2px(height));
        top_heads.setLayoutParams(lp);
        top_heads.setPadding(0, 0, 0, 0);
    }

    protected void onError(Throwable t) {
        Loading.hideDialogForLoading();
        ToastUtils.INSTANCE.showToast(TextUtils.isEmpty(t.getMessage()) ? "未知错误" : t.getMessage());
    }

    protected void call(String phone) {
        Uri uri = Uri.parse("tel:" + phone);
        Intent intent = new  Intent(Intent.ACTION_DIAL,uri);
        startActivity(intent);
    }

}
